import { BrowserRouter, useRoutes } from "react-router-dom";
import React, { Suspense, lazy } from "react";

import Fallback from "./pages/fallback";
import NotFound from "./pages/404";
import Root from "./pages/root";
import { createGlobalStyle } from "styled-components";

const Home = lazy(() => import(/* webpackChunkName: "home" */ "./pages/home"));
const About = lazy(() =>
  import(/* webpackChunkName: "about" */ "./pages/about")
);
const Chart = lazy(() =>
  import(/* webpackChunkName: "chart" */ "./pages/chart")
);

const getLazyComponent = (Child) => (
  <Suspense fallback={<Fallback />}>
    <Child />
  </Suspense>
);

const getFeatureRoute = (path, Element, isLazy = true) => {
  const element = isLazy ? getLazyComponent(Element) : <Element />;
  return {
    path,
    element,
  };
};

const Routes = () =>
  useRoutes([
    getFeatureRoute("/", Root, false),
    getFeatureRoute("*", NotFound, false),
    getFeatureRoute("home", Home),
    getFeatureRoute("about", About),
    getFeatureRoute("chart", Chart),
  ]);

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
`;

const App = () => (
  <>
    <GlobalStyle />
    <BrowserRouter>
      <Routes />
    </BrowserRouter>
  </>
);

export default App;
